/**
 * 通用方法封装处理
 * Copyright (c) 2019
 */
$(function() {

    //  layer扩展皮肤
    if (window.layer !== undefined) {
        layer.config({
            extend: 'moon/style.css',
            skin: 'layer-ext-moon'
        });
    }

    // 回到顶部绑定
    if ($.fn.toTop !== undefined) {
        $('#scroll-up').toTop();
    }

    // select2复选框事件绑定
    if ($.fn.select2 !== undefined) {
        $.fn.select2.defaults.set( "theme", "bootstrap" );
        $("select.form-control:not(.noselect2)").each(function () {
            $(this).select2().on("change", function () {
                $(this).valid();
            })
        })
    }

    // iCheck单选框及复选框事件绑定
    if ($.fn.iCheck !== undefined) {
        $(".check-box:not(.noicheck),.radio-box:not(.noicheck)").each(function() {
            $(this).iCheck({
                checkboxClass: 'icheckbox-blue',
                radioClass: 'iradio-blue',
            })
        })
    }

    // 取消回车自动提交表单
    $(document).on("keypress", ":input:not(textarea):not([type=submit])", function(event) {
        if (event.keyCode == 13) {
            event.preventDefault();
        }
    });

    // 针对ie在input为readonly时选中 点击backspace键会返回上一页的情况
    document.onkeydown =function (e) {
        var ev = e || window.event; //获取event对象
        if (ev.keyCode == 8) {
            var obj = ev.target || ev.srcElement; //获取事件源
            var t = obj.type || obj.getAttribute('type'); //获取事件源类型
            //获取作为判断条件的事件类型
            var vReadOnly = obj.getAttribute('readonly') || obj.readOnly;
            var vdisabled = obj.getAttribute('disabled') || obj.disabled;
            var flag1 = ((t == "password" || t == "text" || t == "textarea"|| t == "email"|| t == "url"|| t == "number"|| t == "range"|| t == "Date"|| t == "search"|| t == "color") && (vReadOnly == true || vdisabled == true)) ? true : false;
            var flag2 = (t != "password" && t != "text" && t != "textarea"&& t != "email"&&t != "url"&& t != "number"&& t != "range"&& t != "Date"&& t != "search"&& t != "color") ? true : false;
            //判断
            if (flag1 || flag2) {
                return false;
            }
        }
    };

    // laydate 时间控件绑定
    if ($(".select-time").length > 0) {
       layui.use('laydate', function() {
            var laydate = layui.laydate;
            var startDate = laydate.render({
                elem: '#startTime',
                max: $('#endTime').val(),
                theme: 'molv',
                type: $('#startTime').attr("data-type") || 'date',
                trigger: 'click',
                done: function(value, date) {
                    // 结束时间大于开始时间
                    if (value !== '') {
                        endDate.config.min.year = date.year;
                        endDate.config.min.month = date.month - 1;
                        endDate.config.min.date = date.date;
                    } else {
                        endDate.config.min.year = '';
                        endDate.config.min.month = '';
                        endDate.config.min.date = '';
                    }
                }
            });
            var endDate = laydate.render({
                elem: '#endTime',
                min: $('#startTime').val(),
                theme: 'molv',
                type: $('#endTime').attr("data-type") || 'date',
                trigger: 'click',
                done: function(value, date) {
                    // 开始时间小于结束时间
                    if (value !== '') {
                        startDate.config.max.year = date.year;
                        startDate.config.max.month = date.month - 1;
                        startDate.config.max.date = date.date;
                    } else {
                        startDate.config.max.year = '2099';
                        startDate.config.max.month = '12';
                        startDate.config.max.date = '31';
                    }
                }
            });
        });
    }

    // laydate time-input 时间控件绑定
    if ($(".time-input").length > 0) {
        layui.use('laydate', function () {
            var com = layui.laydate;
            $(".time-input").each(function (index, item) {
                var time = $(item);
                // 控制控件外观
                var type = time.attr("data-type") || 'date';
                // 控制回显格式
                var format = time.attr("data-format") || 'yyyy-MM-dd';
                // 控制日期控件按钮
                var buttons = time.attr("data-btn") || 'clear|now|confirm', newBtnArr = [];
                // 日期控件选择完成后回调处理
                var callback = time.attr("data-callback") || {};
                if (buttons) {
                    if (buttons.indexOf("|") > 0) {
                        var btnArr = buttons.split("|"), btnLen = btnArr.length;
                        for (var j = 0; j < btnLen; j++) {
                            if ("clear" === btnArr[j] || "now" === btnArr[j] || "confirm" === btnArr[j]) {
                                newBtnArr.push(btnArr[j]);
                            }
                        }
                    } else {
                        if ("clear" === buttons || "now" === buttons || "confirm" === buttons) {
                            newBtnArr.push(buttons);
                        }
                    }
                } else {
                    newBtnArr = ['clear', 'now', 'confirm'];
                }
                com.render({
                    elem: item,
                    theme: 'molv',
                    trigger: 'click',
                    type: type,
                    format: format,
                    btns: newBtnArr,
                    done: function (value, data) {
                        if (typeof window[callback] != 'undefined'
                            && window[callback] instanceof Function) {
                            window[callback](value, data);
                        }
                    }
                });
            });
        });
    }

    // tree 关键字搜索绑定
    if ($("#keyword").length > 0) {
        $("#keyword").bind("focus", function focusKey(e) {
            if ($("#keyword").hasClass("empty")) {
                $("#keyword").removeClass("empty");
            }
        }).bind("blur", function blurKey(e) {
            if ($("#keyword").val() === "") {
                $("#keyword").addClass("empty");
            }
            $.tree.searchNode(e);
        }).bind("input propertychange", $.tree.searchNode);
    }

    // tree表格树 展开/折叠
    var expandFlag;
    $("#expandAllBtn").click(function() {
        var dataExpand = $.common.isEmpty(table.options.expandAll) ? true : table.options.expandAll;
        expandFlag = $.common.isEmpty(expandFlag) ? dataExpand : expandFlag;
        if (!expandFlag) {
            $.bttTable.bootstrapTreeTable('expandAll');
        } else {
            $.bttTable.bootstrapTreeTable('collapseAll');
        }
        expandFlag = expandFlag ? false: true;
    })

    // 按下ESC按钮关闭弹层
    $('body', document).on('keyup', function(e) {
        if (e.which === 27) {
            $.modal.closeAll();
        }
    });
});

(function ($) {
    'use strict';
    $.fn.toTop = function(opt) {
        var elem = this;
        var win = (opt && opt.hasOwnProperty('win')) ? opt.win : $(window);
        var doc = (opt && opt.hasOwnProperty('doc')) ? opt.doc : $('html, body');
        var options = $.extend({
            autohide: true,
            offset: 50,
            speed: 500,
            position: true,
            right: 5,
            bottom: 30
        }, opt);
        elem.css({
            'cursor': 'pointer'
        });
        if (options.autohide) {
            elem.css('display', 'none');
        }
        if (options.position) {
            elem.css({
                'position': 'fixed',
                'right': options.right,
                'bottom': options.bottom,
            });
        }
        elem.click(function() {
            doc.animate({
                scrollTop: 0
            }, options.speed);
        });
        win.scroll(function() {
            var scrolling = win.scrollTop();
            if (options.autohide) {
                if (scrolling > options.offset) {
                    elem.fadeIn(options.speed);
                } else elem.fadeOut(options.speed);
            }
        });
    };
})(jQuery);

/** 刷新选项卡 */
var refreshItem = function(){
    var topWindow = $(window.parent.document);
    var currentId = $('.page-tabs-content', topWindow).find('.active').attr('data-id');
    var target = $('.NAP_iframe[data-id="' + currentId + '"]', topWindow);
    var url = target.attr('src');
    target.attr('src', url).ready();
}

/** 关闭选项卡 */
var closeItem = function(dataId){
	var topWindow = $(window.parent.document);
	if($.common.isNotEmpty(dataId)){
	    window.parent.$.modal.closeLoading();
	    // 根据dataId关闭指定选项卡
	    $('.menuTab[data-id="' + dataId + '"]', topWindow).remove();
	    // 移除相应tab对应的内容区
	    $('.mainContent .NAP_iframe[data-id="' + dataId + '"]', topWindow).remove();
	    return;
	}
	var panelUrl = window.frameElement.getAttribute('data-panel');
	$('.page-tabs-content .active i', topWindow).click();
	if($.common.isNotEmpty(panelUrl)){
	    $('.menuTab[data-id="' + panelUrl + '"]', topWindow).addClass('active').siblings('.menuTab').removeClass('active');
	    $('.mainContent .NAP_iframe', topWindow).each(function() {
	        if ($(this).data('id') == panelUrl) {
	            $(this).show().siblings('.NAP_iframe').hide();
	            return false;
            }
        });
    }
}

/** 创建选项卡 */
function createMenuItem(dataUrl, menuName, isRefresh) {
    var panelUrl = window.frameElement.getAttribute('data-id'),
    dataIndex = $.common.random(1, 100),
    flag = true;
    if (dataUrl == undefined || $.trim(dataUrl).length == 0) return false;
    var topWindow = $(window.parent.document);
    // 选项卡菜单已存在
    $('.menuTab', topWindow).each(function() {
        if ($(this).data('id') == dataUrl) {
            if (!$(this).hasClass('active')) {
                $(this).addClass('active').siblings('.menuTab').removeClass('active');
                scrollToTab(this);
                $('.page-tabs-content').animate({ marginLeft: ""}, "fast");
                // 显示tab对应的内容区
                $('.mainContent .NAP_iframe', topWindow).each(function() {
                    if ($(this).data('id') == dataUrl) {
                        $(this).show().siblings('.NAP_iframe').hide();
                        return false;
                    }
                });
            }
            if (isRefresh) {
            	refreshTab();
            }
            flag = false;
            return false;
        }
    });
    // 选项卡菜单不存在
    if (flag) {
        var str = '<a href="javascript:;" class="active menuTab noactive" data-id="' + dataUrl + '" data-panel="' + panelUrl + '">' + menuName + ' <i class="fa fa-times-circle"></i></a>';
        $('.menuTab', topWindow).removeClass('active');

        // 添加选项卡对应的iframe
        var str1 = '<iframe class="NAP_iframe" name="iframe' + dataIndex + '" width="100%" height="100%" src="' + dataUrl + '" frameborder="0" data-id="' + dataUrl + '" data-panel="' + panelUrl + '" seamless></iframe>';
        $('.mainContent', topWindow).find('iframe.NAP_iframe').hide().parents('.mainContent').append(str1);

        window.parent.$.modal.loading("数据加载中，请稍后...");
        $('.mainContent iframe:visible', topWindow).load(function () {
            window.parent.$.modal.closeLoading();
        });

        // 添加选项卡
        $('.menuTabs .page-tabs-content', topWindow).append(str);
        scrollToTab($('.menuTab.active', topWindow));
    }
    return false;
}

// 刷新iframe
function refreshTab() {
	var topWindow = $(window.parent.document);
	var currentId = $('.page-tabs-content', topWindow).find('.active').attr('data-id');
	var target = $('.NAP_iframe[data-id="' + currentId + '"]', topWindow);
    var url = target.attr('src');
	target.attr('src', url).ready();
}

// 滚动到指定选项卡
function scrollToTab(element) {
    var topWindow = $(window.parent.document);
    var marginLeftVal = calSumWidth($(element).prevAll()),
    marginRightVal = calSumWidth($(element).nextAll());
    // 可视区域非tab宽度
    var tabOuterWidth = calSumWidth($(".content-tabs", topWindow).children().not(".menuTabs"));
    //可视区域tab宽度
    var visibleWidth = $(".content-tabs", topWindow).outerWidth(true) - tabOuterWidth;
    //实际滚动宽度
    var scrollVal = 0;
    if ($(".page-tabs-content", topWindow).outerWidth() < visibleWidth) {
        scrollVal = 0;
    } else if (marginRightVal <= (visibleWidth - $(element).outerWidth(true) - $(element).next().outerWidth(true))) {
        if ((visibleWidth - $(element).next().outerWidth(true)) > marginRightVal) {
            scrollVal = marginLeftVal;
            var tabElement = element;
            while ((scrollVal - $(tabElement).outerWidth()) > ($(".page-tabs-content", topWindow).outerWidth() - visibleWidth)) {
                scrollVal -= $(tabElement).prev().outerWidth();
                tabElement = $(tabElement).prev();
            }
        }
    } else if (marginLeftVal > (visibleWidth - $(element).outerWidth(true) - $(element).prev().outerWidth(true))) {
        scrollVal = marginLeftVal - $(element).prev().outerWidth(true);
    }
    $('.page-tabs-content', topWindow).animate({ marginLeft: 0 - scrollVal + 'px' }, "fast");
}

//计算元素集合的总宽度
function calSumWidth(elements) {
    var width = 0;
    $(elements).each(function() {
        width += $(this).outerWidth(true);
    });
    return width;
}

// 返回当前激活的Tab页面关联的iframe的Windows对象
function activeWindow() {
    var topWindow = $(window.parent.document);
    var currentId = $('.page-tabs-content', topWindow).find('.active').attr('data-id');
    if (!currentId) {
        return window.parent;
    }
    return $('.NAP_iframe[data-id="' + currentId + '"]', topWindow)[0].contentWindow;
}

/** 密码规则范围验证 */
function checkpwd(chrtype, password) {
    if (chrtype == 1) {
        if(!$.common.numValid(password)){
            $.modal.alertWarning("密码只能为0-9数字");
            return false;
        }
    } else if (chrtype == 2) {
        if(!$.common.enValid(password)){
            $.modal.alertWarning("密码只能为a-z和A-Z字母");
            return false;
        }
    } else if (chrtype == 3) {
        if(!$.common.enNumValid(password)){
            $.modal.alertWarning("密码必须包含字母以及数字");
            return false;
        }
    } else if (chrtype == 4) {
        if(!$.common.charValid(password)){
            $.modal.alertWarning("密码必须包含字母、数字、以及特殊符号<font color='red'>~!@#$%^&*()-=_+</font>");
            return false;
        }
    }
    return true;
}

// 日志打印封装处理
var log = {
    log: function(msg) {
        console.log(msg);
    },
    info: function(msg) {
        console.info(msg);
    },
    warn: function(msg) {
        console.warn(msg);
    },
    error: function(msg) {
        console.error(msg);
    }
};

// 本地缓存处理
var storage = {
    set: function(key, value) {
        window.localStorage.setItem(key, value);
    },
    get: function(key) {
        return window.localStorage.getItem(key);
    },
    remove: function(key) {
        window.localStorage.removeItem(key);
    },
    clear: function() {
        window.localStorage.clear();
    }
};

// 主子表操作封装处理
var sub = {
    editColumn: function() {
    	var dataColumns = [];
		for (var columnIndex = 0; columnIndex < table.options.columns.length; columnIndex++) {
    		if (table.options.columns[columnIndex].visible != false) {
    			dataColumns.push(table.options.columns[columnIndex]);
    		}
    	}
		var params = new Array();
		var data = $("#" + table.options.id).bootstrapTable('getData');
    	var count = data.length;
    	for (var dataIndex = 0; dataIndex < count; dataIndex++) {
    	    var columns = $('#' + table.options.id + ' tr[data-index="' + dataIndex + '"] td');
    	    var obj = new Object();
    	    for (var i = 0; i < columns.length; i++) {
    	        var inputValue = $(columns[i]).find('input');
    	        var selectValue = $(columns[i]).find('select');
    	        var textareaValue = $(columns[i]).find('textarea');
    	        var key = dataColumns[i].field;
    	        if ($.common.isNotEmpty(inputValue.val())) {
    	            obj[key] = inputValue.val();
    	        } else if ($.common.isNotEmpty(selectValue.val())) {
    	            obj[key] = selectValue.val();
    	        } else if ($.common.isNotEmpty(textareaValue.val())) {
    	            obj[key] = textareaValue.val();
    	        } else {
    	            obj[key] = "";
    	        }
    	    }
    	    var item = data[dataIndex];
    	    var extendObj = $.extend({}, item, obj);
    	    params.push({ index: dataIndex, row: extendObj });
    	}
    	$("#" + table.options.id).bootstrapTable("updateRow", params);
    },
    delColumn: function(column) {
    	sub.editColumn();
    	var subColumn = $.common.isEmpty(column) ? "index" : column;
    	var ids = $.table.selectColumns(subColumn);
        if (ids.length == 0) {
            $.modal.alertWarning("请至少选择一条记录");
            return;
        }
        $("#" + table.options.id).bootstrapTable('remove', { field: subColumn, values: ids });
    },
    addColumn: function(row, tableId) {
    	var currentId = $.common.isEmpty(tableId) ? table.options.id : tableId;
    	table.set(currentId);
    	var count = $("#" + currentId).bootstrapTable('getData').length;
    	sub.editColumn();
    	$("#" + currentId).bootstrapTable('insertRow', {
            index: count + 1,
            row: row
        });
    }
};

// 动态加载css文件
function loadCss(file, headElem) {
    var link = document.createElement('link');
    link.href = file;
    link.rel = 'stylesheet';
    link.type = 'text/css';
    if (headElem) headElem.appendChild(link);
    else document.getElementsByTagName('head')[0].appendChild(link);
}

// 动态加载js文件
function loadJs(file, headElem) {
    var script = document.createElement('script');
    script.src = file;
    script.type = 'text/javascript';
    if (headElem) headElem.appendChild(script);
    else document.getElementsByTagName('head')[0].appendChild(script);
}

/** 设置全局ajax处理 */
// $.ajaxSetup({
//     complete: function(XMLHttpRequest, textStatus) {
//                 if (textStatus == 'timeout') {
//                     $.modal.alertWarning("服务器超时，请稍后再试！");
//                     $.modal.enable();
//                     $.modal.closeLoading();
//                 } else if (textStatus == "parsererror" || textStatus == "error") {
//                     $.modal.alertWarning("服务器错误，请联系管理员！");
//                     $.modal.enable();
//                     $.modal.closeLoading();
//         }
//     }
// });

Date.prototype.format = function(fmt) {
    var o = {
        "M+" : this.getMonth()+1,                 //月份
        "d+" : this.getDate(),                    //日
        "h+" : this.getHours(),                   //小时
        "m+" : this.getMinutes(),                 //分
        "s+" : this.getSeconds(),                 //秒
        "q+" : Math.floor((this.getMonth()+3)/3), //季度
        "S"  : this.getMilliseconds()             //毫秒
    };
    if(/(y+)/.test(fmt))
        fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
    for(var k in o)
        if(new RegExp("("+ k +")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
    return fmt;
}

String.prototype.trim = function(){
    return this.replace(/^\s+/ , "").replace(/\s+$/ , "");
}

function dropChgSendTextOnly(e,acpId) {
    document.getElementById(acpId).value = e.options[e.selectedIndex].text;
}

function DateToStr() {
    var myTm = new Date();
    var year = myTm.getFullYear();

    var mth = myTm.getMonth()+1;
    if(mth<10)
        mth = "0"+mth;
    var day = myTm.getDate();
    if(day<10)
        day = "0"+day;

    var hour = myTm.getHours();
    if(hour<10)
        hour = "0"+hour;
    var mnt = myTm.getMinutes();
    if(mnt<10)
        mnt = "0"+mnt;

    var scd = myTm.getSeconds();
    if(scd<10)
        scd = "0"+scd;

    var myBack = year+"-"+mth+"-"+day+" "+hour+ ":"+mnt+":"+scd;
    return myBack;
}

function fmtWFormSort(value,row,index){
    var rtn = value;
    var myVal = parseInt(value);
    switch (myVal) {
        case 11:
            rtn = '<div class="spLDark">普通</div>';
            break;
        case 21:
            rtn = '<div class="spOrange">督办</div>';
            break;
        case 31:
            rtn = '<div class="spRed">呈批</div>';
            break;
        case 41:
            rtn = '<div class="spRed">指派</div>';
            break
        default:
            break;
    }
    return rtn;
}

function popupDialog(options) {
    width = options.width || '85%';
    height = options.height || '85%';
    var index = layer.open({
        type: 2,
        area: [height, width],
        fix: false,
        maxmin: false,
        shade: 0.3,
        title: options.title,
        content: options.url,
        btn: ['确定', '关闭'],
        // 弹层外区域关闭
        shadeClose: true,
        yes: function(index, layero) {
            var iframeWin = layero.find('iframe')[0];
            iframeWin.contentWindow.submitHandler();
        },
        cancel: function(index) {
            return true;
        }
    });
}

function winDialog(options) {
    var width = options.width || '85%';
    var height = options.height || '85%';
    var btnArr =  options.btnArr || ['确定', '关闭'];
    var index = top.layer.open({
        type: 2,
        area: [width, height],
        fix: false,
        maxmin: false,
        shade: 0.3,
        title: options.title,
        content: options.url,
        skin: 'layui-layer-gray',
        btn: btnArr,
        // 弹层外区域关闭
        shadeClose: true,
        yes: function(index, layero) {
            var iframeWin = layero.find('iframe')[0];
            iframeWin.contentWindow.submitHandler();
        },
        cancel: function(index) {
            return true;
        }
    });
}

function fmtWFormOpen(value,row,index){
    var rtn = value;
    var myVal = parseInt(value);
    switch (myVal) {
        case 0:
            rtn = '<div class="spLDark">否</div>';
            break;
        case 1:
            rtn = '<div class="spRed">是</div>';
            break;

        default:
            break;
    }
    return rtn;
}



function fmtSBSendState(value,row,index){
    var rtn = value;
    var myVal = parseInt(value);
    switch (myVal) {
        case 0:
            rtn = '<div>none</div>';
            break;
        case 10:
            rtn = '<div class="spRed">未签收</div>';
            break;
        case 11:
            rtn = '<div class="spOrange">再次派单</div>';
            break;

        case 21:
            rtn = '<div class="spBlue">已签收</div>';
            break;
        case 22:
            rtn = '<div class="spOrange">已签(派下级)</div>';
            break;
        case 23:
            rtn = '<div class="spBlue">已签(派下级)</div>';
            break;

        case 30:
            rtn = '<div class="spOrange">撤回</div>';
            break;
        case 40:
            rtn = '<div class="spRed">退回</div>';
            break;
        case 50:
            rtn = '<div class="spRed">退回本级</div>';
            break;
        case 51:
            rtn = '<div class="spRed">拒退</div>';
            break;
        case 60:
            rtn = '<div class="spRed">本级拒退</div>';
            break;
        default:
            break;
    }
    return rtn;
}
function fmtSBBackState(value,row,index){
    var rtn = value;
    var myVal = parseInt(value);
    switch (myVal) {
        case 0:
            rtn = '<div class="spRed">未回复</div>';
            break;
        case 10:
            rtn = '<div class="spLRed">已回(未审)</div>';
            break;

        case 11:
            rtn = '<div class="spLBlue">已回(已审)</div>';
            break;
        case 12:
            rtn = '<div class="spRed">本级不通过</div>';
            break;

        case 21:
            rtn = '<div class="spBlue">上级通过</div>';
            break;
        case 22:
            rtn = '<div class="spRed">上级不通过</div>';
            break;

        default:
            break;
    }
    return rtn;
}
function fmtSBBackCheck(value,row,index){
    var rtn = value;
    var myVal = parseInt(value);
    switch (myVal) {
        case 0:
            rtn = '<div>-</div>';
            break;
        case 10:
            rtn = '<div class="spLRed">未审</div>';
            break;

        case 11:
            rtn = '<div class="spLBlue">自审通过</div>';
            break;
        case 12:
            rtn = '<div class="spRed">自审不通过</div>';
            break;

        case 21:
            rtn = '<div class="spBlue">上级通过</div>';
            break;
        case 22:
            rtn = '<div class="spRed">上级不通过</div>';
            break;

        default:
            rtn = '<div></div>';
            break;
    }
    return rtn;
}

function fmtWFormZP(value,row,index){
    var rtn = value;
    var myVal = parseInt(value);
    switch (myVal) {
        case 1:
            rtn = '<div class="spRed">是</div>';
            break;
        default:
            break;
    }
    return rtn;
}



function fmtDeferState(value,row,index){
    var rtn = value;
    var myVal = parseInt(value);
    switch (myVal) {
        case 0:
            rtn = '<div class="spRed">none</div>';
            break;

        case 10:
            rtn = '<div class="spLRed">待审核</div>';
            break;

        case 21:
            rtn = '<div class="spBlue">同意</div>';
            break;
        case 22:
            rtn = '<div class="spRed">不同意</div>';
            break;

        default:
            break;
    }
    return rtn;
}


function fmtVisitFlag(value,row,index){
    var rtn = value; //VstJudgeCtrl
    var myVal = parseInt(value);
    switch (myVal) {
        case 0:
            rtn = '<div class="spRed">none</div>';
            break;

        case 21:
            rtn = '<div class="spLRed">不满意</div>';
            break;
        case 22:
            rtn = '<div class="spBlue">评价满意</div>';
            break;
        case 25:
            rtn = '<div class="spRed">回访失败</div>';
            break;

        default:
            rtn = '<div class="spRed">none</div>';
            break;
    }
    return rtn;
}

function fmtRecordFlag(value,row,index){
    var rtn = value; //VstJudgeCtrl
    var myVal = parseInt(value);
    switch (myVal) {
        case 0:
            rtn = '<div class="spRed">none</div>';
            break;

        case 20:
            rtn = '<div class="spLRed">未归档</div>';
            break;
        case 21:
            rtn = '<div class="spLBlue">自动</div>';
            break;
        case 22:
            rtn = '<div class="spBlue">归档</div>';
            break;
        case 29:
            rtn = '<div class="spRed">强制</div>';
            break;

        default:
            rtn = '<div class="spRed">none</div>';
            break;
    }
    return rtn;
}
function fmtDerferState(value, row, index) {
    var rtn = value;
    var myVal = parseInt(value);
    switch (myVal) {
        case 10:
            rtn = '<div class="spDGray">未审</div>';
            break;
        case 21:
            rtn = '<div class="spOrange">已审</div>';
            break;
        case 22:
            rtn = '<div class="spOrange">已审</div>';
            break;
        default:
            break;
    }
    return rtn;
}
function fmtTelGetState(value, row, index) {
    var rtn = value;
    var myVal = parseInt(value);
    switch (myVal) {
        case 101:
            rtn = '<div class="spDGray">草稿</div>';
            break;
        case 120:
            rtn = '<div class="spOrange">转后台</div>';
            break;
        case 121:
            rtn = '<div class="spOrange">退回坐席</div>';
            break;
        case 122:
            rtn = '<div class="spLBlue">后台处理中</div>';
            break;
        case 125:
            rtn = '<div class="spBlue">生成工单</div>';
            break;
        case 131:
            rtn = '<div class="spLBlue">话务员办结</div>';
            break;
        case 132:
            rtn = '<div class="spLRed">无效来电</div>';
            break;
        case 135:
            rtn = '<div class="spLRed">值班长作废</div>';
            break;
        case 136:
            rtn = '<div class="spLBlue">值班长办结</div>';
            break;

        default:
            break;
    }
    return rtn;
}

function fmtFmContent(value,row,index){
    var rtn = value;
    if (rtn && rtn.length > 12) {
        rtn = rtn.substr(0,15);
        rtn += '<span data-toggle="tooltip" title="'+value+'">...</span>';
    }
    return rtn;
}

// function showFmContent(obj,value) {
//     alert(0);
// }


function NewTelWinClose(){
    // isOpenRcd = false;
    // $('#telWin').window('lose');
    parent.popIndex = undefined
    $.modal.close();
}

//修改派单
function OnQxListEditWin(action){
    var row = $("#bootstrap-table").bootstrapTable('getSelections');
    var wfId = row[0].WfId;
    var pkId = row[0].myPkVal;
    var url = prefix+'/cmnFile/sendDeptEdit/'+wfId +'/'+pkId;
    var width = '70%';
    var height = '75%';
    var title = '查看-派单';
    if (action == 'check') {
        $.modal.openDialog(title,url,width,height);
    }else{
        var config = {
            id: 'dlSendToSon',
            title: '编辑-派单信息',
            width: width,
            height : height,
            url: url,
            callBack: function(index, layero) {
                var iframeWin = layero.find('iframe')[0];
                iframeWin.contentWindow.submitHandler();
                $.table.refresh();
            }
        };
        $.modal.openOptions(config);
    }
}

//截取年月日
function interceptDate(value,row,index){
    var str = value;
    if (str != '' && str != null) {
        str = str.substr(0,10);
    }
    return str;
}

function setIframeHeight(iframe) {
    if (iframe) {
        var iframeWin = iframe.contentWindow || iframe.contentDocument.parentWindow;
        if (iframeWin.document.body) {
            var height = iframeWin.document.documentElement.scrollHeight || iframeWin.document.body.scrollHeight;
            iframe.height = height;
            console.info(height);
        }
    }
}

function processListWait(id) {
    var url = prefix + "/telHandle/" + id;
    var options = {
        title: "处理待处理来电记录",
        width: '1200px',
        height: '700px',
        url: url,
        skin: 'layui-layer-gray',
        btn: 0,
        shadeClose: false
    };
    $.modal.openOptions(options);
}

function copyBackDesc(obj) {
    var text =$(obj).closest('.ibox-content').find('.replyContent').text();
    var replyIptTxt = $("#backDesc").val();
    if(replyIptTxt.indexOf(text) == -1) replyIptTxt = replyIptTxt + text + '\n\n';
    $("#backDesc").val(replyIptTxt);
}

function cellEllipsis(value, row, index,field) {
    return {
        css:{
            "min-width":"200px",
            "white-space":"nowrap",
            "text-overflow":"ellipsis",
            "overflow":"hidden",
            "max-width":"200px",
        }
    }
}

function lookImage(obj) {
    var wsCode = $('#wsCode').val();
    var ySpare = $('#ySpare').val();
    var index = '';
    if(ySpare.length > 10) {
        if(ySpare.indexOf('mailAccessory') > -1) index = 'mailAccessory';
        else if(ySpare.indexOf('backAccessory') > -1) index = 'backAccessory';
        else if(ySpare.indexOf('BigDataMailAccessory') > -1) index = 'BigDataMailAccessory';
    }
    obj.target = '_blank';
    obj.href = '/system/mail/mailAccessory?wsCode='+wsCode+'&index='+index;
}

$('#tags').on('keyup', function(evt) {
    var evt = window.event ? window.event : evt;
    if(evt.keyCode == 13){
        deptSearch();
    }
});

function refreshCurTab(obj) {
    var topWindow = obj || $(window.top.document);
    var currentId = $('.page-tabs-content', topWindow).find('.active').attr('data-id');
    var target = $('.NAP_iframe[data-id="' + currentId + '"]', topWindow);
    var url = target.attr('src');
    target.attr('src', url).ready();
}

//判断工单是：普通件 临期件 超期件
function rowStyle(row, index) {
    //催办件
    var urgeTransact = {css: {'color':'darkcyan','font-weight':'bold'}};
    var isUrge= row.isUrge;
    if(isUrge === 1){
        return urgeTransact;
    }
    var bl;
    if(row.bkLimit === undefined){
        bl = row.BackLimit.split("-")
    }else{
        bl= row.bkLimit.split("-");
    }
    var current= new Date();
    var cuY=current.getFullYear();
    var cuM=current.getMonth()+1;
    var cuD=current.getDate();
    var redStyle = {css: {'color':'red','font-weight':'bold'}};
    var blueStyle = {css: {'color':'blue','font-weight':'bold'}};
    if(bl[0]>cuY){ //期限年份>当前年份(2015>2014)
        if(getDifferNum(bl[0],bl[1],bl[2],cuY,cuM,cuD) < 2){
            return blueStyle;
        }
        return '';
    } else if(bl[0]<cuY){ //期限年份<当前年份(2014<2015) 超期件
        return redStyle;
    } else{//期限年份=当前日期 年份(2014=2015)
        if(bl[1] > cuM){ //期限月份 > 当前月份 普通件
            if(getDifferNum(bl[0],bl[1],bl[2],cuY,cuM,cuD) < 2){
                return blueStyle;
            }
            return '';
        } else if(bl[1]<cuM){//期限月份 < 当前月份 超期件
            return redStyle;
        } else{
            if(bl[2] > cuD && (bl[2]-cuD) >= 2){
                return '';
            } else if(bl[2] < cuD){//期限日 < 当前日 超期件
                return redStyle;
            } else{ //2天内为 蓝色件
                return blueStyle;
            }
        }
    }
}
//计算时间差值 单位：天
function getDifferNum(sY,sM,sD,eY,eM,eD){
    let startDate = new Date(eY,eM-1,eD) //计算指定日期的总毫秒数
    let endDate = new Date(sY,sM-1,sD) //计算指定日期的总毫秒数
    return (endDate - startDate) / 24 / 60 / 60 / 1000 //相差几天
}

/** 禁用按钮 */
function beforeSend() {
    var $confirmBtn = $('.layui-layer-btn0',top.document);
    $confirmBtn.attr('disabled', true);
    $confirmBtn.addClass('forbidden');
}

/** 启用按钮 */
function completeSend() {
    var $confirmBtn = $('.layui-layer-btn0',top.document);
    $confirmBtn.attr('disabled', false);
    $confirmBtn.removeClass('forbidden');
}

//序号 -- 每页排序
function serialNumber(value, row, index) {
    return index + 1;
}

//序号 -- 翻页递增
function serialNumberToPage(value, row, index) {
    let pageSize=$('#bootstrap-table').bootstrapTable('getOptions').pageSize;
    let pageNumber=$('#bootstrap-table').bootstrapTable('getOptions').pageNumber;
    return pageSize * (pageNumber - 1) + index + 1;
}

function dueWorkOrderCount(value, row, index){
    let dueCount = 0;
    if (value.length !== 0){
        dueCount = value[0].dueCount;
    }
    return "<span style='color: blue;font-size: 15px;'>"+"即将到期件："+dueCount+"件"+"</span>"
}

//临期工单数
function dueWorkOrder(data){
    var data = $("#" + table.options.id).bootstrapTable('getData');
    var newData = [], midData = [];
    var current= new Date();
    var cuY=current.getFullYear();
    var cuM=current.getMonth()+1;
    var cuD=current.getDate();
    var bl;
    for (let i = 0; i < data.length; i++) {
        if(data[i].bkLimit === undefined){
            bl = data[i].BackLimit.split("-")
        }else{
            bl= data[i].bkLimit.split("-");
        }
        if(getDifferNum(bl[0],bl[1],bl[2],cuY,cuM,cuD) < 2){
            newData.push(data[i]) //临期
        }else{
            midData.push(data[i]) //其他
        }
    }
    if (newData.length < data.length){
        newData.push.apply(newData,midData);
    }
    //重新加载数据
    $("#" + table.options.id).bootstrapTable('load', {
        total: $('#bootstrap-table').bootstrapTable('getOptions').totalRows,
        rows: newData
    });
    return false;
}